package org.edu.controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.edu.model.Semester;
import org.edu.service.SemesterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
@SessionScoped
public class SemesterController implements Serializable {

	private static final long serialVersionUID = 1L;
	@Autowired
	private transient SemesterService semesterService;
	private Semester semester;
	private List<Semester> listSemester;

	public SemesterController() {
		semester = new Semester();
	}

	@PostConstruct
	public void init() {
		listSemester = semesterService.semesters();
	}

	public void preparedAdding() {
		semester = new Semester();
	}

	public String save() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		try {
			semester.setStatus_smt(false);
			semesterService.save(semester);
			facesContext.addMessage(null, new FacesMessage("Save Semester is Succesful"));
			init();
			semester = new Semester();
		} catch (Exception e) {
			facesContext.addMessage(null, new FacesMessage("Not Succesful"));
			e.printStackTrace();
		}
		return null;
	}

	public void preparedEditing(Long semester_id) {
		try {
			semester = semesterService.findById(semester_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String update() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		try {
			semesterService.update(semester);
			facesContext.addMessage(null, new FacesMessage("Update Semester is Succesful"));
			init();
			semester = new Semester();
		} catch (Exception e) {
			facesContext.addMessage(null, new FacesMessage("Not Succesful"));
			e.printStackTrace();
		}
		return null;
	}

	public void preparedDeleting(Long semester_id) {
		try {
			semester = semesterService.findById(semester_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String remove() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		try {
			semesterService.remove(semester);
			facesContext.addMessage(null, new FacesMessage(	"Delete Semester is Succesful"));
			init();
			semester = new Semester();
		} catch (Exception e) {
			facesContext.addMessage(null, new FacesMessage("Not Succesful"));
			e.printStackTrace();
		}
		return null;
	}
	
	public Semester getSemester() {
		if (semester == null) {
			semester = new Semester();
		}
		return semester;
	}

	public void setSemester(Semester semester) {
		this.semester = semester;
	}

	public List<Semester> getListSemester() {
		return listSemester;
	}

}
